//var gui = {};

window.gui = typeof process != 'undefined' ? require('nw.gui') : {};
var gInfo = {
    ver: 0.1
};
var isMac = true;//window.navigator.appVersion.indexOf("Mac") != -1;
window.ondragover = function(e) { e.preventDefault(); return false };
window.ondrop = function(e) { e.preventDefault(); return false };

var recentList = [];
window.vehicleData = null;
var imageDir; //当前车型最终保存目录
window.allPhotos = {};

// 在 NW.js 环境中，路径已经在 index.html 中配置
// 这里只需要确保 gui 对象已初始化
if (typeof process !== 'undefined' && !window.gui) {
    window.gui = require('nw.gui');
}
function createVehicle(){
    $$.prompt({
        title : "新建车型", 
        fields : [
            {
                "name": "车型名称："
            }/*,
            {
                "name" : "车型代码：",
                "hint" : "如: BMWX5"
            }*/
        ],
        check : function(arr){
            //var username = (arr[0]||'').trim();
            var code = (arr[0]||'').trim();
            var json = {
                pass : true,
                msg : []
            }
            /*if(username == ''){
                json.msg[0] = "名字不能为空";
                json.pass = false;
            }*/
            if(code == ''){
                json.msg[0] = "代码不能为空";
                json.pass = false;
            }
            if($$.any(recentList, function(item){return item.id==code})){
                json.msg[0] = "代码已存在";
                json.pass = false;
            }
            return json;
        },
        init: function($prompt){
            $$.dom.plugin($prompt.find("input")[0], "modules/inputsug.js");
        },
        callback : function(results){
            recentList.save(results[0]);
            window.imageDir = null;
            window.vehicleData = {
                list: []
            }
        }
    });
}

function safeUrl(url){
    return url = url.replace(/%/g, '%25').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/ /g, '%20').replace(/\\/g, '/');
}

if(typeof process != 'undefined'){
    var fs = require('fs');
    var http = require('http');
    //var iconv = require('iconv-lite');
    //var excel = require('excel-export');
    var path = require('path');
    var gui = window.gui;
    
    // 获取应用根目录（打包后的资源目录）
    var appRoot = (gui.App && gui.App.startPath) || process.cwd();
    var store = require(path.join(appRoot, 'js/store'));  //数据存储

    var $$ = window.bowlder;
    var appDir = gui.App.dataPath.toString() || __dirname; //app临时文件夹

    gInfo.store = store;
    
    var recentFile = appDir + '/recent.js';
    store.localRead(recentFile, function(data){
        recentList = data;
        initVehicle(recentList[0]);
    }, function(){
        initVehicle(recentList[0]);
    });

    recentList.save = function(pageid){
        if(pageid){  //新增打开历史
            clearRecentMenu();
            var item = {
                id: pageid
            }
            for(var i = 0; i < recentList.length; i ++){
                if(recentList[i].id == pageid){
                    item = recentList.splice(i, 1)[0];
                    break;
                }
            }
            recentList.unshift(item);
            insertPageMenu(pageid);
        }
        console.log('recent', recentList);
        store.localSave(recentFile, recentList.slice(0, 15));
    }


    $$.on("vm.initdir", initDir);
    //lsr遍历图片
    function initDir(dir, flag){
        if(dir && gInfo.store){
            var promises = [];
            gInfo.store.readVehicle(dir).then(function(){
                var delay;
                var i = 0;
                var jpgs = gInfo.store.lsr(dir, /\.(jpe?g)$/i);
                var stat = {cn: 0, size: 0};
                jpgs.forEach(function(fileName){
                    stat.cn ++;
                    var file = dir + fileName;
                    stat.size += fs.statSync(file).size;
                });
                if(stat.cn > 200){
                    $$.alert("当前目录文件过多(>200)，请选择子目录。");
                }else if(stat.size > 400*1024*1024){
                    $$.alert("当前目录文件过大(>400M)，请选择子目录。");
                }else{
                    jpgs.forEach(function(fileName){
                        var file = dir + fileName;
                        if(window.allPhotos && window.allPhotos[file]){
                            promises.push($$.Promise.resolve(window.allPhotos[file]));
                            return;
                        }
                        i++;
                        delay = i>30?(i-10)*40:0;
                        promises.push(picReader(file, {
                            url: safeUrl(dir + fileName),
                            path: dir + fileName,
                            name: fileName
                        }, delay));
                        if(delay && (delay % 2000 == 0)){
                            setTimeout(function(){
                                $$.rootWidget.refresh();
                            }, delay);
                        }
                    });
                }
                $$.Promise.all(promises).then(function(fileList){
                    $$.emit("filenav.update", fileList, flag === false ? flag : true); //resetPoints & save data.js
                    $$.rootWidget.refresh();
                });
                if(delay){
                    setTimeout(function(){
                        $$.rootWidget.refresh();
                    }, delay);
                }
            });
        }
    }
    
    function picReader(file, info, delay){
        return new $$.Promise(function(resolve){ //生成缩略图
            window.allPhotos[file] = info; //未转义路径
            file = safeUrl(file);  //%=>%25
            if(delay){
                resolve(info);
                setTimeout(parse, delay);
            }else{
                parse();
            }
            function parse(){
		        var img = document.createElement('img');
		        var canvas = document.createElement('canvas'),
			    ctx = canvas.getContext("2d");
		        img.src = file;
		        img.onload = function(e) {
                    if(img.width/img.height > 100/85){
                        canvas.height = isMac ? 130 : 85;
                        canvas.width = canvas.height/img.height*img.width;
                    }else{
			            canvas.width = isMac ? 150 : 100;
			            canvas.height = (canvas.width/img.width)*img.height;
                    }
			        ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
			        var thumbnail = canvas.toDataURL("image/png");
                    info.thumbnail = thumbnail;
                    if(!delay) resolve(info);
		        };
            }
        })
    }
    
    function initVehicle(vehicle){ //启动或切换车型时：修改title/imageDir
        if(!vehicle){
            createVehicle();
            return;
        }
        if(recentList){
            for(var i = 0; i < recentList.length; i ++){
                if(recentList[i] == vehicle) recentList.splice(i,1);
            }
            recentList.unshift(vehicle);
            recentList.save && recentList.save();
        }

        var vname = (vehicle.name || vehicle.id);
        document.title = "头条汽车点位管理工具 - " + vname;
        document.getElementById("vname").innerHTML = vname;
        imageDir = vehicle.imageDir;
        if(imageDir && fs.existsSync(imageDir)){
            initDir(imageDir);
        }else{
            window.vehicleData = {};
            $$.emit("filenav.update", [], true);
        }
        $$.emit("init.dirname", imageDir);
    }
    
    function clearRecentMenu(){
        if(! menuInfo['车型']) return;
        var len = recentList.length;
        for(var i = 0; i < len; i ++){
            menuInfo['车型'].submenu.removeAt(3);
        }
    }

    function clearMenuTick(menu){
        $$.map(menu.items, function(item){
            if(item.icon == 'images/tick.png') item.icon = '';
        });
    }

    
    function insertPageMenu(pageid){
        if(! menuInfo['车型']) return;
        var len = recentList.length;
        for(var i = len - 1; i >= 0; i --){
            (function(vehicle){
                var menu = {
                    label : (vehicle.name || vehicle.id),
                    click : function(){
                        clearMenuTick(menuInfo['车型'].submenu);
                        this.icon = 'images/tick.png';
                        initVehicle(vehicle);
                    }
                }
                if(i == 0){
                    menu.icon = 'images/tick.png';
                    initVehicle(vehicle);
                }
                menuInfo['车型'].submenu.insert(new gui.MenuItem(menu), 3);
            })(recentList[i]);
        }
        gui.Window.get().menu = win.menu;
    }
    
    var win = gui.Window.get();
    //win.maximize();

    var menuInfo = {
        version : false
    }
    var mainMenu = new gui.Menu({
        type: 'menubar',
	    hideEdit: true,
  	    hideWindow: true
    });
    function openVehicle(){

        $$.prompt({
            title : "打开车型", 
            fields: [
                {
                    "name": "搜索：",
                    "hint": "输入车型名字或代码"
                }
            ],
            check: function(arr){
                var username = arr[0].replace(/^\s+/, '');
                var password = arr[1];
                var json = {
                    pass : true,
                    msg : []
                }
                if(username == ''){
                    json.msg[0] = "搜索词不能为空";
                    json.pass = false;
                }
                return json;
            },
            callback: function(results){
                $$.each(recentList, function(vehicle){
                    if(vehicle.id == results[0]){
                        initVehicle(vehicle);
                    }
                });
            },
            init: function($prompt){
                $$.dom.plugin($prompt.find("input")[0], "modules/inputsug.js").then(function(pluginPromise){
                    pluginPromise.getSuggestion = function(word){
                        var result = [];
                        $$.each(recentList, function(item){
                            if(!word || ~item.id.toLowerCase().indexOf(word.toLowerCase())){
                                result.push(item.id);
                            }
                        });
                        return result;
                    }
                });
            }
        });
    }
    genMenu(mainMenu, {
        '车型' : [
            {
                label : '新建',
                icon : 'images/new.png',
                click : function(){
                    createVehicle();
                }
            },
            {
                label : '打开',
                icon : 'images/fileopen.png',
                click : function(){
                    openVehicle();
                }
            },
            {
                type: 'separator'
            },
            {
                recent: true
            }
        ],
        '工具' : [
            {
                label : '标点工具',
                icon : 'images/edit.png',
                click : function(){
                    location.hash = '#/marker';
                }
            },
            {
                label : '审核工具',
                icon : 'images/tick.png',
                click : function(){
                    location.hash = '#/audit';
                }
            },
            {
                type : 'separator'
            },
            {
                label : '退出',
                icon : 'images/exit.png',
                click : function(){
                    win.close();   
                }
            }
        ],
        '帮助' : [
            {
                label : '开发者工具',
                click : function(){
                    win.showDevTools('', false);
                }
            },
            {
                type: 'separator'
            },
            {
                label : '关于',
                icon : 'images/email.png',
                click : function(){
                    $$.alert("头条汽车点位图工具 v" + gInfo.ver + "\nxiaoyao0315@bytedance.com");
                }
            }
        ]
    });

    win.menu = mainMenu;
    initShortCut();
    initApp();

    function initShortCut(){
        window.onkeyup = function(e){
            var keycode = e.keyCode;
            if(e.ctrlKey){
                if(keycode == 79){  //C-O
                    openVehicle();
                }else if(keycode == 81){  //C-Q
                    win.close();   
                }
            }else{
                if(keycode == 123){  //F12
                    win.showDevTools('', false);   
                }
            }
        };
    }

    function genMenu(menu, json){
        for(var key in json){
            menuInfo[key] = getMenuItem(key, json[key]);
            menu.append(menuInfo[key]);
        }
    }

    function getMenuItem(name, arr){ //生成菜单
        var item = new gui.MenuItem({ label : name });
        if($$.isArray(arr)){
            var submenu = new gui.Menu();
            for(var i = 0; i < arr.length; i ++){
                if(arr[i].type || arr[i].label){
                    var subitem = new gui.MenuItem(arr[i]);
                    submenu.append(subitem);
                }else if(arr[i].recent){
                    $$.map(recentList, function(vehicle){
                        submenu.append(new gui.MenuItem({
                            label : (vehicle.name || vehicle.id),
                            click : function(){
                                initVehicle(vehicle);
                                clearMenuTick(menuInfo['车型'].submenu);
                                this.icon = 'images/tick.png';
                            }
                        }));
                    });
                }
            }
            item.submenu = submenu;
        }
        return item;
    }

    function initApp(){ //初次运行
        var appconf = appDir + "/app.js";
        var firstRun = !fs.existsSync(appconf);
        var username = "";
        var authExpire = false;
        var now = (new Date()).getTime();
        if(firstRun){
            window.appInfo = {
                user : '匿名',
                firstrun : now
            }
        }else{
            store.localRead(appconf, function(data){
                window.appInfo = data;
                username = window.appInfo.user;
                window.appInfo.lastrun = now;
                if((!window.appInfo.authtime || now - window.appInfo.authtime > 7*3600*24*1000)){
                    authExpire = true;
                }else{
                    window.verified = true;
                    store.localSave(appconf, window.appInfo);
                }
            });
        }
        
        if(firstRun){ //|| authExpire
            $$.prompt({
                title : "初次运行向导", 
                fields : [
                    {
                        "name" : "你的名字：",
                        "value" : username
                    }/*,
                    {
                        "name" : "输入口令：",
                        "type" : "password"
                    }*/
                ],
                check : function(arr){
                    var username = arr[0].replace(/^\s+/, '');
                    var password = arr[1];
                    var json = {
                        pass : true,
                        msg : []
                    }
                    if(username == ''){
                        json.msg[0] = "用户名不能为空";
                        json.pass = false;
                    }
                    /*if(password != 'qc@toutiao'){
                      json.msg[1] = "口令不正确";
                      json.pass = false;
                      }*/
                    return json;
                },
                callback : function(results){
                    var username = results[0];
                    if(username){
                        window.verified = true;
                        window.appInfo.user = username;
                        window.appInfo.authtime = now;
                        store.localSave(appconf, window.appInfo);
                    }
                }
            });
        }
    }

    function rmdirRecursive(path) {
        var files = [];
        if( fs.existsSync(path) ) {
            files = fs.readdirSync(path);
            files.forEach(function(file,index){
                var curPath = path + "/" + file;
                if(fs.statSync(curPath).isDirectory()) { // recurse
                    rmdirRecursive(curPath);
                } else { // delete file
                    fs.unlinkSync(curPath);
                }
            });
            fs.rmdirSync(path);
        }
    }
}
function hasPoint(){
    var count = 0;
    $$.each(window.vehicleData.fileMap, function(){count ++});
    return !!count;
}

define(["conf.js"], function(conf){
    var scope = this;
    scope.allPhotos = window.allPhotos;
    var topState = scope.topState = {
        mode: 'marker',
        localDir: "",
        remoteDir: ""
    }
    topState.currentDir = "";
    $$.on("init.dirname", function(dir){
        topState.currentDir = dir || "";
        scope.$refresh();
    }, true);
    
    scope.clearDir = function(){  //清除目录内未归类图片
        topState.currentDir = "";
        $$.emit("filenav.update", [], topState.mode == 'audit');
    }
    scope.showResult = function(){ //report: 审核报表
        var report = {
            count: {
                total: 0,
                standard: 0,
                free: 0,
                fail: 0
            },
            pass: {
                standard: 0,
                free: 0
            },
            fails: {
                '漏点点位': []
            }
        };
        $$.each(conf.pointMap, function(point){
            report.count.total ++;
            var photo = point.photo,
                id = point.id;
            if(!photo){
                report.fails['漏点点位'].push(conf.pointMap[id].label+'('+id+')');
            }else if(photo.audit){
                report.count.standard ++;
                report.pass.standard ++;
            }else if(photo.audit === 0){
                report.count.fail ++;
                var reason = photo.reason || '其它原因';
                if(!report.fails[reason]){
                    report.fails[reason] = [];
                }
                report.fails[reason].push(conf.pointMap[id].label+'('+id+')');
            }
        });
        var reasons = [];
        $$.map(report.fails, function(list, reason){
            reasons.push(reason+'('+list.length+'个): <span style="color:#808080">'+list.join("、")+'</span>');
        });
        var html = $$.template.replace('编号点位数：{{count.total}}个<br/>通过点位数：{{pass.standard+pass.free}}个，漏点点位数{{fails["漏点点位"].length}}个，不通过点位数{{count.fail}}个<br/>'+reasons.join("<br>"), report);
        $$.alert(html);
    }

    // 根据input.files初始化列表
    scope.changeDir = function(e){
        var files = e.target.files;
        if(files.length > 1000){
            alert("文件过多，请选择子目录。");
            return;
        }
        var fileList = [];
        var promises = [];
        var currentDir;
        var file = files[0];
        //file.path: "/Users/xqwei/repos/motor/vehiclemark/images/cut.png"
        //file.name: "ss_rotozoom.jpg"
        //file.webkitRelativePath: "html/img/ss_rotozoom.jpg"
        if(file && file.path && file.webkitRelativePath){
            topState.currentDir = currentDir = file.path.replace(/\\/g, '/');
            if(window.recentList && window.recentList[0]){
                if(topState.mode == 'audit'){
                    initDir(currentDir); //扫描目录
                }else if(!hasPoint()){ //未保存点位时允许切换保存目录
                    gInfo.store.initDir(currentDir);
                    window.imageDir = currentDir;
                    initDir(currentDir); //扫描目录
                }else{
                    initDir(currentDir, false);
                }
            }
        }
    }

});
